//
//  OAuthViewController.swift
//  微博
//
//  Created by admin on 2018/3/23.
//  Copyright © 2018年 xm. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: BaseViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
    }

    override func initView() {
        //取消自动缩进-如果隐藏了导航栏，会缩进20个点
        automaticallyAdjustsScrollViewInsets=false
        setupNavigationBar()
        self.title="授权"
        navItem.leftBarButtonItem=UIBarButtonItem(title: "返回", target: self, action: #selector(canceClick))
        navItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillClick))
        webView.frame=CGRect(x: 0, y: navigationBar.bounds.height,
                             width: view.bounds.width,
                             height: view.bounds.height-navigationBar.bounds.height)
        view.insertSubview(webView, belowSubview: navigationBar)
    }
    
    //webView
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        // urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAPPKEY)&redirect_uri=\(WBREDIRECT_URI)"
        let url = URL(string: urlString)
        //判断字符串是否为nil
        guard let u = url else {
            return webView
        }
        webView.loadRequest(URLRequest(url:u))
        return webView 
    }()
    
    override func loadData(){
        
    }
    
    //取消关闭控制器
    @objc private func canceClick(){
        dismiss(animated: true, completion: nil)
    }
    
    //自动填充
    @objc private func autoFillClick(){
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(12346)';document.getElementById('passwd').value='\(123456)'"
        //JS注入
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
}

// MARK: - WebView代理方法
extension OAuthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.url?.absoluteString
        
        guard let urls=urlString,urls.hasPrefix(WBREDIRECT_URI),// 包含回调地址，说明拿到结果了 就拦截
            let query = request.url?.query,
            let code:String = query.substring(from: "code=".endIndex) //截取字符串得到code值
            else{
                //没有回调地址的一律放行
                return true;
        }
        
        print("=====拿到code===\(code)===")
        NetworkManager.shared.getAccessToken(code: code) { (isSuccess) in
            if isSuccess {
                SVProgressHUD.showInfo(withStatus: "登录成功！")
                NotificationCenter.default.post(name: NSNotification.Name(WBLoginSucceNotification), object: nil)
                self.dismiss(animated: true, completion: nil)
            }else{
                 SVProgressHUD.showInfo(withStatus: "登录授权失败！")
            }
        }
        
        return false
    }
}
